<?php
/**
 * Created by PhpStorm.
 * User: ZhangYi
 * Date: 2011-2-16
 * Time: 11:09:05
 * To change this template use File | Settings | File Templates.
 */

class RetriveGADataTask extends sfBaseTask {

    //map url=>db table name
    private $targets = array('news' => 'News', 'video' => 'Video', 'album' => 'PhotoGroup', 'celebrity' => 'Celebrity');

    protected function configure() {
        parent::configure();
        $this->addOptions(array(new sfCommandOption('max', null,
            sfCommandOption::PARAMETER_REQUIRED, 'max results', PHP_INT_MAX)));
        $this->namespace = 'ieasy';
        $this->name = 'RetriveGAData';
    }

    protected function execute($arguments = array(), $options = array()) {
        //        require_once 'google/gapi-1.3/gapi.class.php';
        try {
            $databaseManager = new sfDatabaseManager($this->configuration);
            require_once dirname(__FILE__) . '/../../lib/vendor/google/gapi-1.3/gapi.class.php';

//            $filter = 'pagePath =@ news || pagePath =@ video || pagePath =@ album || pagePath =@ celebrity
//             && pagePath !@ index.php  && pagePath =@ detail';

            $ga = new gapi('barykan@sina.com', 'easy112233');

            $this->update($ga, 'news');
//            $this->update($ga, 'video');
//            $this->update($ga, 'album');
//            $this->update($ga, 'celebrity');

            echo "update success!\n";
//            $ga->requestReportData(42341062,
//                array('pageTitle', 'pagePath'),
//                array('pageviews', 'visits'),
//                array('-pageviews'), $filter, null, null, 1, $options['max']
//            );
//
//            $tmpArray = array();
//            foreach ($ga->getResults() as $result)
//            {
//                //                echo 'PagePath:', $result->getPagePath() . " ";
//                //                echo 'Pageviews: ' . $result->getPageviews() . ' ';
//                //                echo 'Visits: ' . $result->getVisits() . "\n";
//                $pagePath = $result->getPagePath();
//                $pageViews = $result->getPageviews();
//
//                $splitElems = split('[/.=-]', $pagePath);
//                foreach ($splitElems as $elem) {
//                    if (is_numeric($elem)) {
//                        //                        echo $pagePath . " ";
//                        //                        echo $elem . ' ' . $pageViews . " \n";
//                        if (!array_key_exists($elem, $tmpArray))
//                            $tmpArray[$elem] = $pageViews;
//                        else
//                            $tmpArray[$elem] += $pageViews;
//                        break;
//                    }
//                }
//            }
//            foreach ($tmpArray as $key => $value)
//            {
//                echo $key . " " . $value . " \n";
//                $news = Doctrine::getTable('News')->find($key);
//                $news->setHitI($value);
//                $news->save();
//            }

        } catch (Exception $e) {
            echo $e->getMessage() . "\n";
            echo $e->getTraceAsString();

        }
    }

    private function update(gapi $ga, $urlFacet) {
        $filter = 'pagePath =@ news || pagePath =@ video || pagePath =@ album || pagePath =@ celebrity && pagePath !@ index.php  && pagePath =@ detail';

        $ga->requestReportData(42341062,
            array('pageTitle', 'pagePath'),
            array('pageviews', 'visits'),
            array('-pageviews'), $filter, null, null, 1, PHP_INT_MAX
        );

        $tmpArray = array('news' => array(), 'video' => array(), 'album' => array(), 'celebrity' => array());
        foreach ($ga->getResults() as $result)
        {
            $pagePath = $result->getPagePath();
            $pageViews = $result->getPageviews();

//            echo $pagePath . " " . $pageViews . " ";

            $splitElems = split('[/.=-]', $pagePath);

            $facet = "";
            foreach ($this->targets as $urlKey => $tableName) {
                if (strpos($pagePath, $urlKey)!==FALSE) {
                    //                    $tmpArray[$urlKey] = array();
                    $facet = $urlKey;
//                    echo $urlKey . " ";
                    break;
                }
            }

            foreach ($splitElems as $elem) {
                if (is_numeric($elem)) {
                    echo $elem . " ";
                    if (!array_key_exists($elem, $tmpArray[$facet]))
                        $tmpArray[$facet][$elem] = $pageViews;
                    else
                        $tmpArray[$facet][$elem] += $pageViews;
                    echo  $tmpArray[$facet][$elem] . " \n";
                    break;
                }
            }
        }

//        echo $DbTableName . ": \n";
//        print_r($tmpArray);
        echo "updating...\n";
        foreach ($tmpArray as $key => $subArray)
        {
            //            echo $key . " " . $value . " \n";
            $tableName = $this->targets[$key];

//            echo $tableName . ": \n";

            foreach ($subArray as $id => $hit) {
//                echo $id . " " . $hit . "\n";
                $entity = Doctrine::getTable($tableName)->find($id);
                if ($entity) {

                    $entity->setHitI($hit);
                    $entity->save();
                }
            }
        }

                $this->updatePeriodData($ga, $urlFacet);
    }

    private function updatePeriodData(gapi $ga, $urlFacet) {
        $today = date('Y-m-d');
        $lastmonth = date('Y-m-d', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")));
        $lastweek = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));

        $startDates = array('today' => $today, 'lastweek' => $lastweek, 'lastmonth' => $lastmonth);

        $filter = 'pagePath =@ news || pagePath =@ video || pagePath =@ album || pagePath =@ celebrity
         && pagePath !@ index.php  && pagePath =@ detail';
        $DbTableName = "";
        switch ($urlFacet)
        {
            case 'news':
                $DbTableName = 'News';
                break;
            case 'video':
                $DbTableName = 'Video';
                break;
            case 'album':
                $DbTableName = 'PhotoGroup';
                break;
            case 'celebrity':
                $DbTableName = 'Celebrity';
                break;
            default:
                return;
        }

        foreach ($startDates as $dateKey => $startdate) {

            echo $dateKey . ": \n";
            $ga->requestReportData(42341062,
                array('pageTitle', 'pagePath'),
                array('pageviews', 'visits'),
                array('-pageviews'), $filter, $startdate, null, 1, PHP_INT_MAX
            );

            $tmpArray = array('news' => array(), 'video' => array(), 'album' => array(), 'celebrity' => array());
            foreach ($ga->getResults() as $result)
            {
                $pagePath = $result->getPagePath();
                $pageViews = $result->getPageviews();

                $splitElems = split('[/.=-]', $pagePath);

                $facet = "";
                foreach ($this->targets as $urlKey => $tableName) {
                    if (strpos($pagePath, $urlKey)!==FALSE) {
                        //                        $tmpArray[$urlKey] = array();
                        $facet = $urlKey;
                        break;
                    }
                }
                foreach ($splitElems as $elem) {
                    if (is_numeric($elem)) {
                        if (!array_key_exists($elem, $tmpArray[$facet]))
                            $tmpArray[$facet][$elem] = $pageViews;
                        else
                            $tmpArray[$facet][$elem] += $pageViews;
                        break;
                    }
                }
            }
            echo $DbTableName . ": \n";
            foreach ($tmpArray as $key => $subArray)
            {
//                                echo $key . " " . $value . " \n";
                $tableName = $this->targets[$key];
//                echo $tableName . ": \n";
                foreach ($subArray as $id => $hit) {
                    try {
                        $entity = Doctrine::getTable($tableName)->find($id);
                        if ($entity) {
                            switch ($dateKey) {
                                case 'today' :
                                    $entity->setDailyHit($hit);
                                    break;
                                case 'lastweek':
                                    $entity->setWeeklyHit($hit);
                                    break;
                                case 'lastmonth':
                                    $entity->setMonthlyHit($hit);
                                    break;
                            }
//                            echo $id . " " . $hit . "\n";
                            $entity->save();
                        }
                    } catch (Exception $e)
                    {

                    }
                }
            }
        }
    }
}
